<?php

namespace app\api\controller;

use addons\shopro\model\Order;
use app\admin\model\share\CommonShare;
use \app\admin\model\share\ShareUser;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Sms;
use app\common\model\RechargeFenConfig;
use app\common\model\User as FUser;
use app\common\model\UserChangeLog;
use app\common\model\userIdCard;
use think\Db;

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test', 'cancellation', 'cancellation', 'test_fz'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function test()
    {
        RechargeFenConfig::get();
        $user_id = input('user_id');
        $userModel = new \app\admin\model\share\ShareUser();
        $uidArrAll = $userModel->getTeamUser($user_id);
        $this->success('返回成功', $this->request->param());
    }

    /**
     * 无需登录的接口
     *
     */
    public function test1()
    {

        $list = Db::name("tp_users")->select();
        $in_data = [];
        foreach ($list as $k => $v) {
            $in_data[] = [
                'user_number' => $v['user_number'],
                'nickname' => $v['nickname'],
                'user_grade' => $v['user_grade'],
                'pid_number' => $v['pid_number'],
                'user_money' => $v['user_money'],
                'intro_ids' => $v['path'],
                'mobile' => $v['mobile'],
            ];
        }
        $in_status = Db::name("user_team_all")->insertAll($in_data);
        $this->success('返回成功', ['action' => 'test1']);
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $goods = Db::name("shopro_order")->group("goods_id")->select();
        $re_data = [];
        foreach ($goods as $k => $v) {
            if (!$v['goods_id']) continue;
            $saleNum = Db::name("shopro_order")->where('status', 'in', '1,2')->where(["goods_id" => $v['goods_id']])->count();
            $t_d = strtotime(date('Y-m-d', time()));
            $todaySaleNum = Db::name("shopro_order")->where('status', 'in', '1,2')->where(["goods_id" => $v['goods_id']])->where('createtime', '>', $t_d)->count();
            $yest_time = date("Y-m-d", strtotime("-1 day"));
            $end_time = date('Y-m-d 00:00:00');
            $yesterdaySaleNum = Db::name("shopro_order")->where('status', 'in', '1,2')->where(["goods_id" => $v['goods_id']])->where('createtime', 'between time', [$yest_time, $end_time])->count();
            $re_data[] = [
                "goodsId" => $v['goods_id'],
                "yesterdaySaleNum" => $yesterdaySaleNum,
                "todaySaleNum" => $todaySaleNum,
                "saleNum" => $saleNum
            ];
        }
        $this->success('返回成功', $re_data);
        $d_data['url'] = 'https://' . $_SERVER['HTTP_HOST'];
        $d_data['uid'] = 17191;
        $d_data['amount'] = 17191;
        $d_data['tel'] = 15958407177;

        $re_data = $this->curl_post("https://d-xwzt.bigchun.com/api/index/getMoney", $d_data);

        $re_data = json_decode($re_data[0]);
        if ($re_data->code == 0) {
            $this->error($re_data->msg);
        }
        $this->success('返回成功', ['action' => 'test2']);
    }

    protected function curl_post($url, $uriParam)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 使用命令不执行
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        // curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($uriParam)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_POSTFIELDS, is_array($uriParam) ? http_build_query($uriParam) : $uriParam); // Post提交的数据包
        // curl_setopt($curl, CURLOPT_POSTFIELDS,$uriParam); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        // curl_setopt($curl, CURLOPT_HTTPHEADER,['Content-type:application/json']); // 设置头部
        curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type:application/x-www-form-urlencoded']); // 设置头部
        $res = curl_exec($curl); // 执行操作
        $errno = curl_errno($curl);
        curl_close($curl); // 关闭CURL会话
        return [$res, $errno];
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }

    // function add_user()
    // {
    //     for ($i = 0; $i < 400; $i++) {
    //         $num = rand(10, 99);
    //         $phone = '135000011' . $num;
    //         $exist = Db::name("user")->where("mobile", $phone)->find();
    //         if (!$exist) {
    //             $param = [
    //                 'mobile' => $phone,
    //                 'type' => 1,
    //                 'captcha' => 1234,
    //                 'invitecode' => input('invitecode'),
    //             ];
    //             $this->curlPost('https://xingwu.bigchun.com/api/user/mobilelogin', $param);
    //         }

    //         $count =  Db::name("user")->count();
    //         if($count > 41) break;

    //     }
    // }

    // function curlPost($url, $data = [])
    // {
    //     $ch = curl_init();
    //     curl_setopt($ch, CURLOPT_POST, 1);
    //     curl_setopt($ch, CURLOPT_HEADER, 0);
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //     curl_setopt($ch, CURLOPT_URL, $url);
    //     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    //     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //     $result = curl_exec($ch);
    //     curl_close($ch);
    //     return $result;
    // }

    // function create_order()
    // {
    //     $list = Db("user")->select();
    //     foreach ($list as $v) {
    //         $exist = Db::name('shopro_order')->where('user_id', $v['id'])->find();
    //         if (!$exist) {
    //             Db::name('shopro_order')->insert([
    //                 'type' => 'goods',
    //                 'order_sn' => 'pnt04nfx8sy933333youzv7c1' . rand(1000000, 9999999),
    //                 'user_id' => $v['id'],
    //                 'activity_type' => null,
    //                 'goods_amount' => '3599.00',
    //                 'dispatch_amount' => '0.00',
    //                 'phone' => '15252525252',
    //                 'consignee' => '测试',
    //                 'province_name' => '北京市',
    //                 'city_name' => '东城区',
    //                 'area_name' => '北京市',
    //                 'address' => '测试',
    //                 'province_id' => '110000',
    //                 'city_id' => '110100',
    //                 'area_id' => '110101',
    //                 'status' => '1',
    //                 'invoice_status' => '-1',
    //                 'memo' => null,
    //                 'remark' => null,
    //                 'total_amount' => '3599.00',
    //                 'score_amount' => '0',
    //                 'total_fee' => '3599.00',
    //                 'discount_fee' => '0.00',
    //                 'coupon_fee' => '0.00',
    //                 'activity_discount_money' => '0.00',
    //                 'dispatch_discount_money' => '0.00',
    //                 'pay_fee' => '3599.00',
    //                 'score_fee' => '0',
    //                 'goods_original_amount' => '3599.00',
    //                 'coupons_id' => '0',
    //                 'transaction_id' => null,
    //                 'payment_json' => null,
    //                 'pay_type' => 'wallet',
    //                 'paytime' => '1664196097',
    //                 'ext' => null,
    //                 'platform' => 'App',
    //                 'xw_orderNo' => '',
    //                 'xw_account' => '',
    //                 'xw_code' => '',
    //                 'createtime' => time(),
    //                 'updatetime' => time(),
    //                 'deletetime' => null,
    //                 'is_share' => '0',
    //                 'goods_id' => '2'
    //             ]);
    //         }
    //     }
    // }

    public function user_in($pids = '688872')
    {
        // Db::startTrans();
        $add_data_all = [];
        $where['pid_number'] = ['in', $pids];
        $ut_data = Db::name('user_test')->where($where)->select();
        if ($pids == '688872') {
            $ut1 = Db::name('user_test')->where(['user_number' => '688872'])->find();
            $add_data_all[] = [
                'nickname' => $ut1['nickname'],
                'user_money' => $ut1['user_money'],
                'user_number' => $ut1['user_number'],
                'pid_number' => $ut1['pid_number'],
                'user_grade' => $ut1['user_grade'],
                'intro_ids' => $ut1['intro_ids'],
                'mobile' => $ut1['mobile'],
                'user_score' => $ut1['user_score'],
                'user_old_money' => $ut1['user_old_money'],
                'mutual_money' => $ut1['mutual_money'],
                'advert_price' => $ut1['advert_price'],
                'lp_price' => $ut1['lp_price'],
            ];
        }

        if ($ut_data) {
            $pids = '';
            foreach ($ut_data as $k => $v) {
                $pids .= $v['user_number'] . ',';
                $add_data_all[] = [
                    'nickname' => $v['nickname'],
                    'user_money' => $v['user_money'],
                    'user_number' => $v['user_number'],
                    'pid_number' => $v['pid_number'],
                    'user_grade' => $v['user_grade'],
                    'intro_ids' => $v['intro_ids'],
                    'mobile' => $v['mobile'],
                    'user_score' => $v['user_score'],
                    'user_old_money' => $v['user_old_money'],
                    'mutual_money' => $v['mutual_money'],
                    'advert_price' => $v['advert_price'],
                    'lp_price' => $v['lp_price'],
                ];

            }
            $in_status = Db::name("user_test_1")->insertAll($add_data_all);
            if (!$in_status) {
                // Db::rollback();
                echo "添加失败";
                exit;
            }
            self::user_in(trim($pids, ","));
        }
        //Db::commit();
        echo '成功';
        exit;
    }

    public function user_yan($pids = '36017')
    {

        // Db::startTrans();
        $add_data_all = [];
        $where['pid_number'] = ['in', $pids];
        $ut_data = Db::name('user_test_yan')->where($where)->select();
        if ($pids == '36017') {
            $ut1 = Db::name('user_test_yan')->where(['user_number' => '36017'])->find();

            $add_data_all[] = [
                'nickname' => $ut1['nickname'],
                'price' => $ut1['price'],
                'old_price' => $ut1['old_price'],
                'score' => $ut1['score'],
                'mutual_money' => $ut1['mutual_money'],
                'user_number' => $ut1['user_number'],
                'pid_number' => $ut1['pid_number'],
                'user_grade' => $ut1['user_grade'],
                'intro_ids' => $ut1['intro_ids'],
                'mobile' => $ut1['mobile'],
            ];
        }

        if ($ut_data) {
            $pids = '';
            foreach ($ut_data as $k => $v) {
                $pids .= $v['user_number'] . ',';
                $add_data_all[] = [
                    'nickname' => $v['nickname'],
                    'price' => $v['price'],
                    'old_price' => $v['old_price'],
                    'score' => $v['score'],
                    'mutual_money' => $v['mutual_money'],
                    'user_number' => $v['user_number'],
                    'pid_number' => $v['pid_number'],
                    'user_grade' => $v['user_grade'],
                    'intro_ids' => $v['intro_ids'],
                    'mobile' => $v['mobile'],
                ];

            }

            $in_status = Db::name("user_test_yan_1")->insertAll($add_data_all);
            if (!$in_status) {
                // Db::rollback();
                echo "添加失败";
                exit;
            }
            self::user_yan(trim($pids, ","));
        }
        //Db::commit();
        echo '成功';
        exit;
    }

    public function shuju_yan()
    {
        $list = Db::name("user_test_yan_1")->select();
        Db::startTrans();
        foreach ($list as $k => $v) {
            $user_data = Db::name("user")->where(['mobile' => $v['mobile']])->find();
            $save_data = Db::name("share_user")->where(['user_id' => $user_data['id']])->update(['price' => $v['price'], 'old_price' => $v['old_price'], 'score' => $v['score'], 'mutual_money' => $v['mutual_money']]);
            if (!$save_data) {
                Db::rollback();
            }
        }
        Db::commit();
    }
//     public function add_user(){
//         $mobile = $this->request->post("mobile");
//         $nickname = $this->request->post("nickname");
//         if(!$mobile || !$nickname){
//             echo "缺少必传参数";exit;
//         }
//         $where['role'] = ['>',0];
//        $user_d = Db::name("share_user")->where($where)->order("user_id desc")->find();
//         $add_data_all = [
//             'nickname' => $nickname,
//             'username' => $mobile,
//             'password' =>  '5f1d7a84db00d2fce00b31a7fc73224f',
//             'salt' =>  '123456',
//             'invitecode' =>$this->english_num(),
//             'mobile' => $mobile,
//             'createtime' =>time(),
//             'status'=>'normal',
//             'parent_user_id'=>$user_d['user_id'],
//             'pid'=>$user_d['user_id'],
//         ];
//         $in_id = Db::name("user")->insertGetId($add_data_all);
//         (new ShareUser())->add_user($user_d['user_id'], $in_id,  $user_d['user_id'],1);
//         echo "成功";
//     }
//    public function up_role()
//    {
//        $id = $this->request->post("id");
//        if(!$id){
//            echo "ID必传";exit;
//        }
//        $where['id'] =$id;
//        //$where['parent_user_id'] = null;
//        $u_data = Db::name("share_user")->where($where)->order('id','desc')->select();
//        foreach ($u_data as $k=>$v){
//            (new ShareUser())->promotion_save($v['parent_id'],$v['role'],$v['role_type']);
//        }
//        echo "成功";
//    }
//    private function english_num()
//    {
//        $s = '0123456789';
//        $temp = '';
//        while (strlen($temp) < 6) {
//            $index = mt_rand(0, strlen($s) - 1);
//            $temp .= $s[$index];
//        }
//        return $temp;
//    }
//    public function up_share(){
//        $where['id'] = ['>',1];
//        //$where['parent_user_id'] = null;
//        $u_data = Db::name("share_user")->where($where)->select();
//        foreach ($u_data as $k=>$v){
//            $temp_data = Db::name("share_user")->where(['parent_id'=>$v['user_id']])->select();
//            if($v['role'] >= 2 && count($temp_data) < 3){
//                echo '下线小于3的ID：'.$v['user_id'].'\n';
//            }
//            foreach ($temp_data as $key => $value) {
//                $role_type = $key+1;
//                $save_status = Db::name("share_user")->where(['id'=>$value['id']])->update(['role_type'=>$role_type]);
//                if ($key > 2) {
//                    echo '下线大于3的ID：'.$value['parent_id'].'\n';
//                }
//            }
//        }
//        $this->up_share2();
//        echo "成功";
//    }
//
//    public function up_share2(){
//        $u_data = Db::name("share_user")->order('id desc')->select();
//        foreach ($u_data as $k=>&$v){
//            // 上级数量加 1
//            if (!empty($v['role_url'])) {
//                $parents = explode('/',$v['role_url']);
//                foreach ($parents as $key => $value) {
//                    if ($key >= 1) {
//                        $this->sum_amount($parents[$key]);
//                    }
//                }
//            }
//        }
//    }
//    public function sum_amount($user_id)
//    {
//        $user_id = $this->request->post("id");
//        if(!$user_id){
//            echo "ID必传";exit;
//        }
//        $user =(new ShareUser())->get(['user_id'=>$user_id]); // 分销用户
//        $user->amount = bcadd($user['amount'],1);
//        $user->save();
//        echo "成功";
//    }
//  public function setpad(){
//      $params['password'] = $this->getEncryptPassword("rykj@2022$#", 'sssfff');
//      $params['salt'] = 'sssfff';
//      $s_status = Db::name("admin")->where(['id'=>1])->update($params);
//      if($s_status){
//          echo "成功";
//      }else{
//          echo "失败";
//      }
//  }
//    public function getEncryptPassword($password, $salt = '')
//    {
//        return md5(md5($password) . $salt);
//    }
//    public function re_add_user(){
//        $nickname = $this->request->post("nickname");
//        $mobile = $this->request->post("mobile");
//        $score = $this->request->post("score");
//        $price = $this->request->post("price");
//        $role = $this->request->post("role");
//        $password = $this->request->post("password");
//        $salt = $this->request->post("salt");
//        $refund_fee = $this->request->post("refund_fee");
//        $url = $this->request->post("url");
//        if(empty($nickname) || empty($mobile)){
//            return "缺少必传参数".$nickname ."||". $mobile ."||". $score ."||". $price ."||". $role ."||". $refund_fee;
//        }
//        $u_data = Db::name("user")->where(["mobile"=>$mobile])->find();
//        Db::startTrans();
//        $add_data_all = [
//            'nickname' => $nickname,
//            'username' => $mobile,
//            'password' =>  $password,
//            'salt' =>  $salt,
//            'mobile' => $mobile,
//            'createtime' =>time(),
//            'status'=>'normal',
//            'url'=>$url,
//        ];
//        $in_id = Db::name("user")->insertGetId($add_data_all);
//        $add_share_user = [
//            'user_id' => $in_id,
//            'role' => $role,
//            'addtime' =>  time(),
//            'price' =>  $price,
//            'score' => $score,
//            'refund_fee' =>$refund_fee,
//        ];
//        $add_status = Db::name("share_user")->insert($add_share_user);
//        if($in_id && $add_status){
//            Db::commit();
//            return "success";
//        }else{
//            Db::rollback();
//            return "失败";
//        }
//    }
    /**
     * 感谢支持退货用
     * 注销用户
     */
    public function cancellation()
    {
        $ip = $_SERVER["REMOTE_ADDR"];
        if($ip != "112.74.190.90"){
            $re_data['status'] = "ip错误";
            return json_encode($re_data);
        }
        $mobile = $this->request->post("mobile");
        if(!$mobile){
            $re_data['status'] = "缺少必传参数";
            return json_encode($re_data);
        }

        $users = Db::name("user")->where(["mobile"=>$mobile])->find();
        if(!$users){
            $re_data['status'] = "手机号不存在";
            return json_encode($re_data);
        }
        Db::startTrans();
        $user_id = $users['id'];
        $before_mobile = $users['mobile'];
        $mobile = '199'.rand(10000000,99999999);
        $re_users['mobile'] = $mobile;
        $re_users['username'] = $mobile;
        $save1 = Db::name("user")->where(['id'=>$user_id])->update($re_users);
        // 删除实名认证
        //$save2 = userIdCard::where('user_id', '=', $user_id)->delete();
        $Share_data =  (new ShareUser())->where(['user_id'=>$user_id])->find();
        $ShareUser =  (new ShareUser())->where(['amount'=>0, 'role'=>0,'user_id'=>$user_id])->find();
        if (!empty($ShareUser)) {
            Db::name("share_user")->where(['user_id' =>$user_id])->delete();
            $in_da = ['user_id' => $user_id, 'before_mobile' => $before_mobile, 'after_mobile' => 0, 'memo' => '退货直接删除用户'];
            Db::name("user_change_log")->insert($in_da);
            //UserChangeLog::create(['user_id' => $user_id, 'before_mobile' => $before_mobile, 'after_mobile' => 0, 'memo' => '退货直接删除用户']);
        } else {
            $in_da = ['user_id' => $user_id, 'before_mobile' => $before_mobile, 'after_mobile' => $mobile, 'memo' => '退货删除用户变更手机号'];
            Db::name("user_change_log")->insert($in_da);
            //UserChangeLog::create(['user_id' => $user_id, 'before_mobile' => $before_mobile, 'after_mobile' => $mobile, 'memo' => '退货删除用户变更手机号']);
        }
        if(!$save1){
            Db::rollback();
            return "操作失败".$save1;
        }
        //删除好友关系
        (new CommonShare())->delUserf($user_id);
        Db::commit();
        $d_data['mobile'] = $before_mobile;
        $fgurl = Db::name("config")->where(['name'=>'5gurl'])->value('value');
        $g_data = $this->curl_post($fgurl."/api/user/zhuxiao", $d_data);
        $re_data['status'] = "success";
        $re_data['price'] = $Share_data['price'];
        $re_data['score'] = $Share_data['score'];
        return json_encode($re_data);
    }

    public function test_fz()
    {
        (new CommonShare())->orderBillAdd();
    }
}
